import axios from 'axios';

interface Cast {
    date: string;
    week: string;
    dayweather: string;
    nightweather: string;
    daytemp: string;
    nighttemp: string;
    daypower: string;
    nightpower: string;
    daytemp_float: string;
    nighttemp_float: string;
}

interface WeatherForecast {
    city: string;
    adcode: string;
    province: string;
    reporttime: string;
    casts: Cast[];
}

interface WeatherResponse {
    status: string;
    count: string;
    info: string;
    infocode: string;
    forecasts: WeatherForecast[];
}

// 请求天气数据的函数
export async function getWeatherData(cityCode: string, apiKey: string): Promise<WeatherResponse | null> {
    const url = `https://restapi.amap.com/v3/weather/weatherInfo?city=${cityCode}&key=${apiKey}&extensions=all&output=JSON`;

    try {
        const response = await axios.get<WeatherResponse>(url);

        // 判断请求是否成功
        if (response.data.status === '1') {
            return response.data;
        } else {
            console.error('Error fetching weather data:', response.data.info);
            return null;
        }
    } catch (error) {
        console.error('Request failed', error);
        return null;
    }
}

// 格式化天气数据的函数
export function formatWeatherData(response: WeatherResponse) {
    if (response.status !== '1') {
        console.error('Error fetching weather data:', response.info);
        return;
    }

    const forecast = response.forecasts[0];
    const casts = forecast.casts;

    const today = casts[0];
    const tomorrow = casts[1];

    const formatWeather = (dayweather: string, nightweather: string, daytemp: string, nighttemp: string) => {
        return dayweather === nightweather
            ? `${dayweather} ${daytemp}/${nighttemp}°C`
            : `${dayweather}转${nightweather} ${daytemp}/${nighttemp}°C`;
    };

    // 输出今天和明天的天气
    const todayWeather = formatWeather(today.dayweather, today.nightweather, today.daytemp, today.nighttemp);
    const tomorrowWeather = formatWeather(tomorrow.dayweather, tomorrow.nightweather, tomorrow.daytemp, tomorrow.nighttemp);

    console.log(`今天 ${todayWeather}`);
    console.log(`明天 ${tomorrowWeather}`);

    return { todayWeather, tomorrowWeather };
}